package licode.unisop.platform.adapter.web;

import licode.unisop.client.utils.PlatformCheck;
import licode.unisop.platform.client.info.PlatformAuthInfo;
import licode.unisop.platform.client.info.PlatformHeartInfo;
import licode.unisop.platform.client.vo.PlatAuthVO;
import licode.unisop.provider.info.SiPlatIdFind;
import licode.unisop.provider.info.SiPlatformId;
import licode.unisop.unilite.result.UniResult;
import licode.unisop.unilite.result.UniReturnResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import licode.unisop.platform.application.executor.SiPlatformAuthExecutor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author licode
 */
@Slf4j
@RestController
@UniReturnResult
@RequestMapping("/plat-api/v1/internal/auth")
public class PlatformAuthAdapter {
    @Resource
    private HttpServletRequest request;
    
    @Resource
    private PlatformCheck platformCheck;

    @Resource
    private SiPlatformAuthExecutor platformAuthExecutor;

    /**
     * 验证平台（各个平台登录时调用）
     * @param info 平台认证的信息
     * @return 返回临时生成的平台Token
     */
    @PostMapping("/register")
    public UniResult<PlatAuthVO> register(@RequestBody PlatformAuthInfo info) {
        return UniResult.of(platformAuthExecutor.register(info));
    }

    /**
     * 通过平台标识查询平台信息
     * @param idInfo 平台标识
     * @return 平台信息
     */
    @PostMapping("/from-id")
    public UniResult<PlatAuthVO> fromId(@RequestBody SiPlatIdFind idInfo) {
        platformCheck.checkModalToken(request);
        return UniResult.of(platformAuthExecutor.fromId(idInfo));
    }

    /**
     * 获取当前已经认证的平台数
     * @return 认证的平台数
     */
    @PostMapping("/count")
    public UniResult<Long> getAuthCount() {
        return UniResult.of(platformAuthExecutor.getAuthCount());
    }

    /**
     * 对指定的平台进行禁用
     * @param idInfo 平台ID
     */
    @PostMapping("/forbid")
    public UniResult<String> forbid(@RequestBody SiPlatformId idInfo) {
        platformAuthExecutor.forbid(idInfo);
        return UniResult.of("ok");
    }

    /**
     * 对认证的平台进行续期
     * @param info 平台信息
     * @return 成功返回OK
     */
    @PostMapping("/renew-duration")
    public UniResult<String> renew(@RequestBody PlatformHeartInfo info) {
        return UniResult.of(platformAuthExecutor.renew(info));
    }
}
